﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using OpenFaq.Core.UserModule;

namespace OpenFaq.Core
{
	public class OpenFaqContext : DbContext
	{
		public OpenFaqContext()
		{
		}

		public DbSet<User> Users { get; set; }
		public DbSet<Role> Roles { get; set; }

		public static void DropCreateDatabaseIfModelChanges()
		{
			Database.SetInitializer<OpenFaqContext>(new DropCreateDatabaseIfModelChanges<OpenFaqContext>());
			//new DropCreateDatabaseAlways<OpenFaqContext>()
			//new DropCreateDatabaseIfModelChanges<OpenFaqContext>());
			//new CreateDatabaseOnlyIfNotExists<OpenFaqContext>());

			EnsureDbCreated();
		}

		public static void DropCreateDatabaseAlways()
		{
			Database.SetInitializer<OpenFaqContext>(new DropCreateDatabaseAlways<OpenFaqContext>());
		
			EnsureDbCreated();
		}

		private static void EnsureDbCreated()
		{
			//Ensure that DB is created at his point
			//Need to do this or TransactionScope in TestInitialize will cause MSDTC error when DbContext is actually used
			//for the first time, since that's when the DB creation is deferred to.
			using (var db = new OpenFaqContext())
			{
				//This will create database
				db.Users.FirstOrDefault(usr => usr.Username == "test");
			}
		}
	}
}
